//
//  FFLoading.m
//  FFAirUILoading
//
//  Created by chewyong on 2017/7/27.
//  Copyright © 2017年 isoftstone. All rights reserved.
//

#import "FFLoading.h"
// #import "MBProgressHUD.h"
#import <MBProgressHUD/MBProgressHUD.h>

#define kTimeoutSeconds 15.f
#define kLabelFont 16.f
#define kStatusBarHeight 20
#define kNavigationBarHeight 44
#define kTabBarHeight 49

@interface FFLoading () <MBProgressHUDDelegate> {
    BOOL _isTimeOut;
    UITapGestureRecognizer *_hideHudGesture;
    BOOL _isTapHide;    // 是否是手势隐藏了提示框
}
@property(nonatomic, strong) MBProgressHUD *hud;
@property(nonatomic, strong) NSTimer *timer;
@property(nonatomic, strong) UIView *promptView;
@end
@implementation FFLoading

#pragma mark - Initialization

+ (FFLoading *)sharedInstance {
    static id gSharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
      gSharedInstance = [[FFLoading alloc] init];
    });
    return gSharedInstance;
}

- (id)init {
    self = [super init];
    if (self) {
        self.promptViewLevel = FFViewLevel;    // 默认加载提示信息时不允许用户进行操作
        self.isOpenHiddenGesture = NO;         // 关闭隐藏提示框的手势
        self.isOpenTimeOut = NO;               // 关闭超时提醒
    }
    return self;
}

// 懒加载
- (UIView *)promptView {
    if (_promptViewLevel == FFWindowLevel) {
        self.promptView = [UIApplication sharedApplication].keyWindow;
    } else {
        self.promptView = [[UIWindow alloc] initWithFrame:CGRectMake(0, kStatusBarHeight + kNavigationBarHeight, [UIScreen mainScreen].bounds.size.width,
                                                                     [UIScreen mainScreen].bounds.size.height - kStatusBarHeight - kNavigationBarHeight - kTabBarHeight)];
        _promptView.hidden = NO;    // 必要的设置
    }

    return _promptView;
}

#pragma mark - Class Methods

+ (void)showHudWithText:(NSString *)textString {
    dispatch_block_t block = ^{
      [[FFLoading sharedInstance] dismiss];
      [[FFLoading sharedInstance] showHudWithText:textString];
    };
    if ([NSThread isMainThread]) {
        block();
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
          block();
        });
    }
}

+ (void)dismiss {
    dispatch_block_t block = ^{
      [[FFLoading sharedInstance] dismiss];
    };
    if ([NSThread isMainThread]) {
        block();
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
          block();
        });
    }
}

+ (void)showHudWithText:(NSString *)textString duration:(NSTimeInterval)duration {
    dispatch_block_t block = ^{
      [[FFLoading sharedInstance] dismiss];
      [[FFLoading sharedInstance] showHudWithText:textString duration:duration];
    };
    if ([NSThread isMainThread]) {
        block();
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
          block();
        });
    }
}

+ (void)showAutomicHiddenHudText:(NSString *)textString {
    dispatch_block_t block = ^{
      [[FFLoading sharedInstance] showHudWithText:textString duration:2.0f];
    };
    if ([NSThread isMainThread]) {
        block();
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
          block();
        });
    }
}

+ (void)showHudWithCustomView:(UIView *)customView {
    dispatch_block_t block = ^{
      [[FFLoading sharedInstance] showHudWithCustomView:customView];
    };
    if ([NSThread isMainThread]) {
        block();
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
          block();
        });
    }
}

+ (bool)isShowing {
    return [[FFLoading sharedInstance] isShowing];
}

#pragma mark - show & hide

- (void)showHudWithCustomView:(UIView *)customView {
    self.hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];

    self.hud.mode = MBProgressHUDModeCustomView;
    self.hud.customView = customView;
    self.hud.delegate = self;

    [self setHideHudGesture];
}

- (void)showHudWithText:(NSString *)textString {
    self.hud = [MBProgressHUD showHUDAddedTo:self.promptView animated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.delegate = self;

    self.hud.detailsLabel.font = [UIFont boldSystemFontOfSize:kLabelFont];
    self.hud.detailsLabel.text = textString;

    [self setHideHudGesture];

    if (_isOpenTimeOut) {    // 开启超时提醒
        _isTimeOut = YES;
        _isTapHide = NO;
        [self createTimer];
    }
}

- (void)showHudWithText:(NSString *)textString duration:(NSTimeInterval)duration {
    self.hud = [MBProgressHUD showHUDAddedTo:self.promptView animated:YES];
    self.hud.mode = MBProgressHUDModeText;

    // self.hud.detailsLabelFont = [UIFont boldSystemFontOfSize:kLabelFont];
    // self.hud.detailsLabelText = textString;
    self.hud.detailsLabel.text = textString;
    self.hud.detailsLabel.font = [UIFont boldSystemFontOfSize:kLabelFont];

    self.hud.delegate = self;

    //[self.hud hide:YES afterDelay:duration];
    [self.hud hideAnimated:YES afterDelay:duration];
    [self setHideHudGesture];
}

- (void)createTimer {
    if (!self.timer) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:kTimeoutSeconds target:self selector:@selector(handleTimeOut) userInfo:nil repeats:NO];
    }
}

- (void)destroyTimer {
    if ([self.timer isValid]) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)handleTimeOut {
    if (!_isTapHide && _isTimeOut) {
        // 提示超时
        [[self class] showHudWithText:NSLocalizedString(@"AllVC_Execute_TimeOut", nil) duration:1.f];
    }
}

- (void)setHideHudGesture {
    if (_isOpenHiddenGesture) {
        [self addHideHudGesture];
    } else {
        [self removeHideHudGesture];
    }
}

- (void)addHideHudGesture {
    if (!_hideHudGesture) {
        _hideHudGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideProgressHUD:)];
    }

    [self.hud addGestureRecognizer:_hideHudGesture];
}

- (void)hideProgressHUD:(UITapGestureRecognizer *)tap {
    _isTapHide = YES;

    [self dismiss];
}

- (void)removeHideHudGesture {
    if (_hideHudGesture) {
        [self.hud addGestureRecognizer:_hideHudGesture];
    }
}

- (void)dismiss {
    [MBProgressHUD hideHUDForView:self.promptView animated:YES];

    self.hud = nil;
    self.promptView = nil;

    [self destroyTimer];
    _isTimeOut = NO;
}

- (bool)isShowing {
    if (_hud != nil) {
        return true;
    }
    if (_promptView != nil) {
        return true;
    }
    return false;
}

- (void)dealloc {
    if (self.hud) {
        self.hud.delegate = nil;
    }
}

#pragma mark - MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud {
    [self dismiss];

    //    NSLog(@"hud was hidden");
    if (self.hudWasHiddenBlock) {
        self.hudWasHiddenBlock(_isTimeOut);
    }
}

@end
